//
//  AFAppDotNetAPIClient.m
//  LiHai
//
//  Created by YAO on 15/4/15.
//  Copyright (c) 2015年 YAO. All rights reserved.
//

#import "AFAppDotNetAPIClient.h"
#import "UrlManage.h"
#import "SecurityUtil.h"
#import<CommonCrypto/CommonDigest.h>




@interface AFAppDotNetAPIClient ()

+ (instancetype)sharedClient;

@end

@implementation AFAppDotNetAPIClient


+ (instancetype)sharedClient {
    
    static dispatch_once_t once;
    static AFAppDotNetAPIClient *sharedView;
    dispatch_once(&once, ^ {
        sharedView = [[self alloc] initWithBaseURL:[NSURL URLWithString:
                                                    [UrlManage sharedManager].baseUrl]];
    });
    return sharedView;
}

#pragma mark - header封装
- (instancetype)initWithBaseURL:(NSURL *)url {
    
    self = [super initWithBaseURL:url];
    if (self) {
        self.requestSerializer = [AFJSONRequestSerializer serializer];
        
        self.responseSerializer = [AFJSONResponseSerializer serializer];

        self.responseSerializer=[AFHTTPResponseSerializer serializer];
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/xml",
                                                          @"text/html",
                                                          @"text/json",
                                                          @"text/javascript",
                                                          @"text/plain",
                                                          @"text/json",
                                                          nil];
        
        self.requestSerializer.timeoutInterval = 30.0;
        [self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"content-type"];
        [self.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    }
    return self;
}

#pragma mark - get请求
+ (void)getAsynchronous:(NSString *)path
              parameter:(NSDictionary *)dic
           successBlock:(HTTPRequestFinishingHandler)successBlock
             errorBlock:(HTTPRequestFailedHandler)errorBlock {
    
    [[self sharedClient] GET:path parameters:dic progress:nil
                     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                         
                         NSDictionary *dict = [[self sharedClient]
                                               dataOrStringToDictionary:responseObject];
                         
                         if (dict) {
                             
                             successBlock(dict,nil);
                         }
                         
                     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                         
                         errorBlock(error);
                     }];
}

#pragma mark - post请求
+ (void)postAsynchronous:(NSString *)path
               parameter:(id)dic
            successBlock:(HTTPRequestFinishingHandler)successBlock
              errorBlock:(HTTPRequestFailedHandler)errorBlock {
    
    [[self sharedClient] POST:path parameters:dic progress:nil
                      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                          
                          NSDictionary *dict = [[self sharedClient]
                                                dataOrStringToDictionary:responseObject];
                          
                          if (dict)
                          {
                              successBlock(dict,nil);
                              return ;
                          }
                          
                          NSString *str = [[self sharedClient]
                                                dataTOjsonString:responseObject];
                          
                          if (![str isEqualToString:@""]&& str !=nil) {
                              NSDictionary *dict = @{@"data":str};
                              successBlock(dict,nil);
                              return;
                          }
                          
                          NSDictionary *dictToDict =  [[self sharedClient]
                                                  dataToDictionary:responseObject];
                          if (dictToDict)
                          {
                              successBlock(dictToDict,nil);
                              return ;
                          } else {
                              errorBlock(nil);
                          }
                          
                      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                          
                          errorBlock(error);
                      }];
}

#pragma mark - put请求
+ (void)putAsynchronous:(NSString *)path
              parameter:(id)dic
           successBlock:(HTTPRequestFinishingHandler)successBlock
             errorBlock:(HTTPRequestFailedHandler) errorBlock{
    
    
    [[self sharedClient] PUT:path parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = [[self sharedClient]
                              dataOrStringToDictionary:responseObject];
        if (dict)
        {
            successBlock(dict,nil);
        } else {
            errorBlock(nil);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorBlock(error);
    }];

}


- (NSDictionary *)dataOrStringToDictionary:(id)object {
    
    if ([object isKindOfClass:[NSData class]]) {
        
        return [self dataToDictionary:object];
        
    }else if ([object isKindOfClass:[NSString class]]) {
        
        NSData *data = [object dataUsingEncoding:NSUTF8StringEncoding];
        
        return [self dataToDictionary:data];
        
    }else if ([object isKindOfClass:[NSDictionary class]]) {
        
        return (NSDictionary *)object;
    }
    
    return nil;
}

- (NSDictionary *)dataToDictionary:(NSData *)date {
    
    NSError *error = nil;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:date
                                                         options:NSJSONReadingMutableContainers
                                                           error:&error];
    return dict;
}

- (NSString *)dataTOjsonString:(id)object {

    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if ( !jsonData ) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

@end
